package com.gaoch.simweather.logic.network

import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.lang.RuntimeException
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine

object SimWeatherNetwork {
    private val placeService=ServiceCreator.createPlace<PlaceService>()
    suspend fun searchPlaces(query:String)= placeService.searchPlaces(query).await()

    private val weatherService=ServiceCreator.createWeather<WeatherService>()
    suspend fun getNowWeather(location:String)= weatherService.getNowWeather(location).await()
    suspend fun getDailyWeather(location: String)= weatherService.getDailyWeather(location).await()
    suspend fun getAqi(location: String)= weatherService.getAqi(location).await()
    suspend fun getHourlyWeather(location: String)= weatherService.getHourlyWeather(location).await()

    private suspend fun <T> Call<T>.await():T{
        return suspendCoroutine { continuation ->
            enqueue(object : Callback<T> {
                override fun onResponse(call: Call<T>, response: Response<T>) {
                    val body=response.body()
                    if(body!=null)continuation.resume(body)
                    else continuation.resumeWithException(RuntimeException("response body is null"))
                }

                override fun onFailure(call: Call<T>, t: Throwable) {
                    continuation.resumeWithException(t)
                }
            })
        }
    }
}